package cc.eddic.pratice.programmingparadigms.emp02list.impl;

import cc.eddic.pratice.programmingparadigms.Result;
import cc.eddic.pratice.programmingparadigms.emp02list.ResultList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ResultListTyqImpl implements ResultList {

    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);

    private Result[] results;

    public ResultListTyqImpl() {
        this(10);
    }

    public ResultListTyqImpl(int capacity) {
        results = new Result[capacity];
    }

    public ResultListTyqImpl(Result[] results) {
        this(results.length * 2);
        // TODO:
        for (Result result : results) {
            add(result);
        }
    }

    public ResultListTyqImpl(ResultList results) {
        this(results.size() * 2);
        // TODO:
        for (int i = 0; i < results.size(); i++) {
            add(results.get(i));
        }
    }

    @Override
    public void add(Result result) {
        if (size() == results.length) {
            if (log.isDebugEnabled()) {
                log.debug("上一个ResultList已满，长度为：{}，正在扩容。。。", size());
            }
            ResultListTyqImpl resultListTyq = new ResultListTyqImpl(size() + 1);
            for (Result result1 : results) {
                resultListTyq.add(result1);
            }
            resultListTyq.add(result);
            results = resultListTyq.results;
            if (log.isDebugEnabled()) {
                log.debug("扩容成功，扩容后当前长度为：{}", size());
            }
        } else {
            results[size()] = result;
        }
    }

    @Override
    public Result get(int index) throws IndexOutOfBoundsException {
        if (index > size() - 1) {
            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
        }
        return results[index];
    }

    @Override
    public int size() {
        int count = 0;
        for (Result result : results) {
            if (null != result) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }

    @Override
    public Result findByGender(String gender) {
        for (int i = 0; i < size(); i++) {
            if (get(i).getKey().equals(gender)) {
                return get(i);
            }
        }
        return null;
    }

    @Override
    public Result findByDepartment(String department) {
        for (int i = 0; i < size(); i++) {
            if (get(i).getKey().equals(department)) {
                return get(i);
            }
        }
        return null;
    }

    @Override
    public Result findByJobTitle(String jobTitle) {
        for (int i = 0; i < size(); i++) {
            if (get(i).getKey().equals(jobTitle)) {
                return get(i);
            }
        }
        return null;
    }
}
